<?php

namespace App\Http\Controllers\API;

use App\Models\Admin;
use App\Models\Cart;
use App\Models\Goods;
use App\Models\Order;
use App\Models\Province;
use App\Repositories\UsersRepository;
use App\User;
use App\ZL\Controllers\ApiBaseController;
use App\ZL\Library\ErrorCode;
use App\ZL\ORG\Xcx\Common;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class UsersController extends ApiBaseController
{
    protected $user;
    protected $store;
    protected $order;

    public function __construct(UsersRepository $usersRepository)
    {
        $this->user = $usersRepository;
    }

    public function userInfo()
    {
        $user = Auth::user();

        $ps = Province::all()->keyBy('value');
        $user->address_str = '';
        if($user->province)
            $user->address_str .= $ps[$user->province]->text;

        if($user->city)
            $user->address_str .= $ps[$user->city]->text;
        if($user->district)
            $user->address_str .= $ps[$user->district]->text;
        return responseZK(1,$user->toArray());
    }

    public function setInfo(Request $request)
    {
        $user = Auth::user();
        $data = $request->all();
        unset($data['uid']);
        User::where('id',$user->id)->update($data);
        return responseZK(1,User::find($user->id));
    }

    public function sendVerifyCode(Request $request)
    {
        $mobile_code = rand(100000,999999);
        $mobile = $request->tel;
        $mobile = $mobile?$mobile:$request->phone;
        $type = $request->type;
        if($type=='register' && $this->checkTel($mobile)){
            $res = responseZK(0,null,'此手机号已经注册');
        }elseif($type=='findPassword' && !$this->checkTel($mobile)){
            $res = responseZK(0,null,'此手机号没有注册');
        }else{
            //   阿里大鱼
            $send_result = sendVerifyCode($mobile, $mobile_code);
            if($send_result['status']==1){
                $res = responseZK(1,$mobile_code,'验证码发送成功');
                Cache::put('verify_tel_'.$mobile, $mobile_code, 300);
            }else{
                $res['status']=0;
                $res['msg']='验证码发送失败！';
//                $value = Cache::pull('verify_tel_'.$mobile);
                $res = responseZK(0,null,$send_result['msg']);
            }
        }
        return $res;
    }

    public function setVerifyCode(Request $request)
    {
        $mobile = $request->tel;
        $mobile_code = $request->code;
        $mobile = $mobile?$mobile:$request->phone;
        if($this->checkTel($mobile)){
            $res = responseZK(0,null,'此手机号已经注册');
        }elseif($mobile_code!=Cache::get('verify_tel_'.$mobile)){
            $res = responseZK(0,null,'验证码错误');
        }else{
            $user = Auth::user();
            $user->phone = $mobile;
            $user->save();
            $res = responseZK(1,$mobile_code,'设置成功');
        }
        return $res;
    }

    public function findPassword(Request $request)
    {
        $mobile = $request->tel;
        $password = $request->password;
        $mobile_code = $request->code;
        $mobile = $mobile?$mobile:$request->phone;
        $user = $this->checkTel($mobile);
        if(!$user){
            $res = responseZK(0,null,'找不到手机号');
        }elseif($mobile_code!=Cache::get('verify_tel_'.$mobile)){
            $res = responseZK(0,null,'验证码错误');
        }else{
            $user->password = bcrypt($password);
            $user->save();
            $res = responseZK(1,$mobile_code,'设置成功');
        }
        return $res;
    }

    public function register(Request $request)
    {
        $mobile = $request->tel;
        $mobile_code = $request->code;
        $mobile = $mobile?$mobile:$request->phone;
        if(!$mobile){
            $res = responseZK(0,null,'请输入手机号');
        }elseif($this->checkTel($mobile)){
            $res = responseZK(0,null,'此手机号已经注册');
        }elseif($mobile_code!=Cache::get('verify_tel_'.$mobile)){
            $res = responseZK(0,null,'验证码错误');
        }else{
            $data = [
                'phone'=>$mobile,
                'name'=>$request->name,
                'password'=>bcrypt($request->password),
                'sex'=>$request->sex,
                'province'=>$request->province,
                'city'=>$request->city,
                'district'=>$request->district,
                'address'=>$request->address,
                'company_name'=>$request->company_name,
            ];
            $user = User::create($data);
            $res = responseZK(1,$user,'注册成功');
        }
        return $res;
    }

    public function likeGoodsIndex(Request $request)
    {
        
    }

    public function likeGoods(Request $request)
    {
        $user = Auth::user();
        $data = Goods::find($request->goods_id);
        if($data){
            $data->read_num++;
            $data->save();
        }
        $user->likes()->attach($request->goods_id);
        return responseZK(1);
    }

    public function unLikeGoods(Request $request)
    {
        $user = Auth::user();
        $data = Goods::find($request->goods_id);
        if($data){
            $data->read_num--;
            $data->save();
        }
        $user->likes()->detach($request->goods_id);
        return responseZK(1);
    }

    public function addCart(Request $request)
    {
        $user = Auth::user();
        if(!$user)
            return responseZK(0,null, '请先登录');
        $has = Cart::where([
            ['goods_id',$request->goods_id],
            ['user_id',$user?$user->id:null],
            ['color_id',$request->color_id],
        ])->first();
        if($has){
            $has->number+=$request->number;
            $has->save();
        }else{
            $has = Cart::create([
                'goods_id'=>$request->goods_id,
                'user_id'=>$user?$user->id:null,
                'color_id'=>$request->color_id,
                'number'=>$request->number,
            ]);
        }
        return responseZK(1,$has);
    }

    public function setCart(Request $request)
    {
        $user = Auth::user();
        $has = Cart::where([
            ['goods_id',$request->goods_id],
            ['user_id',$user->id],
            ['color_id',$request->color_id],
        ])->first();
        if($has){
            $has->number = $request->number;
            $has->save();
            if($request->number<=0){
                $has->delete();
            }
        }else{
            $has = Cart::create([
                'goods_id'=>$request->goods_id,
                'number'=>$request->number,
                'user_id'=>$user->id,
                'color_id'=>$request->color_id,
            ]);
        }
        return responseZK(1,$has);
    }

    public function login(Request $request)
    {
        $mobile = $request->phone;
        $password = $request->password;
        if(!$mobile){
            $res = responseZK(0,null,'请输入手机号');
        }else{
            $user = $this->checkTel($mobile);
            if($user){
                $ok = auth()->guard('web')->attempt(['phone'=>$mobile,'password'=>$password]);
                if($ok){
                    $res = responseZK(1,$user,'登录成功');
                }else{
                    $res = responseZK(0,null,'账户或者密码错误');
                }
            }else{
                $res = responseZK(0,null,'账户或者密码错误');
            }
        }
        return $res;
    }

    public function passwordUpdate(Request $request)
    {
        $password = \request('password');
        $old_password = \request('old_password');
        $user = Auth::user();
        if($user){
            if(!Hash::check($old_password, $user->password))
                return responseZK(0,null,'旧密码错误');
            $user->password = bcrypt($password);
            $user->save();
            return responseZK(1,$user);
        }else{
            return responseZK(0,null,'未登录');
        }
    }

    public function checkTel($tel)
    {
        return User::where('phone',$tel)->first();
    }

    public function customerAdd(Request $request)
    {
        $input = $request->all();
        $input['type'] = 2;
        $input['parent_id'] = Auth::id();
        $user = User::create($input);
        return responseZK(1,$user,'成功');
    }

    public function customerUpdate($id, Request $request)
    {
        $u_m = new User();
        User::where('id', $id)->update($request->only($u_m->fillable));

        $customer = User::find($id);
        return responseZK(1,$customer,'成功');
    }

    public function customerDel($id, Request $request)
    {
        $customer = User::find($id);
        $has = Order::where('customer_id',$id)->first();
        if($has){
            return responseZK(0,null,'客户有订单，无法删除！');
        }else{
            if($customer)
                $customer->delete();
            return responseZK(1,null,'删除成功！');
        }
    }

    public function customerIndex(Request $request)
    {
        $list = Auth::user()->customers()->orderBy('name','asc')->get();
        $ps = Province::all()->keyBy('value');
        foreach ($list as &$v) {
            $v->address_str = '';
            if($v->province)
                $v->address_str .= $ps[$v->province]->text;
            if($v->city)
                $v->address_str .= $ps[$v->city]->text;
            if($v->district)
                $v->address_str .= $ps[$v->district]->text;

        }
        return responseZK(1,$list,'成功');
    }

    public function customerInfo($id, Request $request)
    {
        $v = User::find($id);
        $ps = Province::all()->keyBy('value');
        $v->address_str = '';
        if($v->province)
            $v->address_str .= $ps[$v->province]->text;

        if($v->city)
            $v->address_str .= $ps[$v->city]->text;
        if($v->district)
            $v->address_str .= $ps[$v->district]->text;
        return responseZK(1,$v,'成功');
    }

    public function adminEditPassword(Request $request)
    {
        $old = $request->old_password;
        $new = $request->new_password;
        $id = $request->id;

        $admin = Admin::find($id);
        if(!Hash::check($old, $admin->password)){
            return responseZK(0,null,'旧密码错误');
        }else{
            $admin->password = bcrypt($new);
            $admin->save();
            return responseZK(1,null,'修改成功');
        }
    }
}
